package org.csu.linkgame.controller;

import com.leewyatt.rxcontrols.controls.RXTranslationButton;
import de.felixroske.jfxsupport.FXMLController;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.stage.Stage;
import org.csu.linkgame.service.UserService;
import org.csu.linkgame.utils.AlertView;
import org.csu.linkgame.utils.ServiceUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.URL;
import java.util.ResourceBundle;

@FXMLController
public class RegisterViewController implements Initializable {

    @FXML
    private TextField usernameTextField;
    @FXML
    private PasswordField passwordTextField;
    @FXML
    private RXTranslationButton registerButton;

    @Autowired
    private UserService userService;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
    }

    public void handleRegisterButtonAction(ActionEvent actionEvent) {
        AlertView alertView = new AlertView(Alert.AlertType.NONE);
        String username = usernameTextField.getText();
        String password = passwordTextField.getText();

        int i = ServiceUtil.serviceUtil.userService.userRegister(username, password);
        if (i == 0) {
            // 用户名已经被注册！
            System.out.println("用户名已经被注册！");
            usernameTextField.setText("");
            passwordTextField.setText("");
            alertView.showAlert(Alert.AlertType.WARNING, "警告", "用户名已经被注册！", ButtonType.OK);
        } else if (i == 1) {
            ServiceUtil.serviceUtil.logService.insertLog(username + "成为了新用户");
            // 注册成功！
            alertView.showAlert(Alert.AlertType.INFORMATION, "提示", "注册成功！！！", ButtonType.OK);
            // 获取当前窗口
            Stage window = (Stage) registerButton.getScene().getWindow();
            // 关闭窗口
            window.close();
        } else {
            // 注册失败！
            alertView.showAlert(Alert.AlertType.ERROR, "错误", "注册失败！！！", ButtonType.OK);
       }
    }

    public void handleCancelButtonAction(ActionEvent event) {
        // 获取当前窗口
        Stage window = (Stage) registerButton.getScene().getWindow();
        // 关闭窗口
        window.close();
    }
}
